package com.zmyuan.demo.netty.thrift.rpc;

import com.zmyuan.demo.netty.thrift.*;
import com.zmyuan.demo.netty.thrift.utils.ThriftUtils;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

/**
 * Created by zdb on 2017/2/17.
 */
public class FrameworkThriftRPCClient {

    public static <T> T startClient(int port, ThriftRequest request, Class<T> tClass) throws Exception {
        TTransport tTransport = new TFramedTransport(new TSocket("localhost", port));
        TProtocol protocol = new TBinaryProtocol(tTransport);
        FrameworkService.Client client = new FrameworkService.Client(protocol);

        tTransport.open();
        ThriftResponse response = client.execut(request);
        return ThriftUtils.convertBytesToObject(response.getBody(), tClass);
    }

    public static void main(String[] args) throws Exception {
        ThriftRequest req = new ThriftRequest();
        req.setCommand("saveContent");
        Content content = new Content();
        content.setId(1);
        content.setPhone("18812345678").setPrice(11);
        req.setRequestParam(ThriftUtils.convertThriftObjToBytes(content));

        Content rc = startClient(8999, req, Content.class);
        System.out.println(rc.getPhone());
    }
}
